<?php
namespace App\Repository\Java;

use App\Exceptions\ValidateException;

/**
 * User: HuangYin
 * Date: 2017-01-10 14:44
 *
 * Description:
 */

abstract class Repository
{
    protected $prefix;

    public function __construct()
    {
        $this->setPrefix();
    }

    abstract protected function setPrefix();

    public function post($functionName, $data, $isLogin = false)
    {
        $data = json_encode($data);
        $url = env('JAVA_RESOURCE'). $this->prefix . $functionName . '.jhtml';
        $result = $this->curlSet($url, $isLogin, $data);
        if (is_null(json_decode($result))) {
            $this->curlSet(env('JAVA_RESOURCE').'system/login.jhtml', true,
                json_encode(['userName' => env('JAVA_USERNAME'), 'password' => env('JAVA_PASSWORD')])
            );
            $result = $this->curlSet($url, $isLogin, $data);
        }

        return json_decode($result, true);
    }

    public function get($url, $data, $isLogin = false)
    {
        $data = json_encode($data);
        $result = $this->curlSet($url, $isLogin, $data);
        if (is_null(json_decode($result))) {
            $this->curlSet(env('JAVA_RESOURCE').'system/login.jhtml', true,
                json_encode(['userName' => env('JAVA_USERNAME'), 'password' => env('JAVA_PASSWORD')])
            );
            $result = $this->curlSet($url, $isLogin, $data);
        }

        return json_decode($result, true);
    }

    protected function curlSet($url, $isLogin, $data)
    {
        $header = ['Content-Type: application/json'];
        $cookieJar = 'temp/' . scandir('temp', 1)[0];
        if ($isLogin) {
            if (!file_exists('temp'))
                mkdir('temp');
            unlink($cookieJar);
            $cookieJar = tempnam('temp', 'javaCookie');
        }
        $process = curl_init($url);
        curl_setopt($process, CURLOPT_HTTPHEADER, $header);
        curl_setopt($process, CURLOPT_TIMEOUT, 30);
        curl_setopt($process, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($process, CURLOPT_POSTFIELDS, $data);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        if ($isLogin) {
            curl_setopt($process, CURLOPT_COOKIEJAR, $cookieJar);
        } else {
            curl_setopt($process, CURLOPT_COOKIEFILE, $cookieJar);
        }
        curl_setopt($process, CURLOPT_POST, 1);
        $result = curl_exec($process);
        curl_close($process);

        return $result;
    }

    /**
     * 10000 z c n m
     *
     * @param $functionName
     * @param $data
     * @param bool $isLogin
     * @param int $timeOut
     * @return array|mixed
     * @throws ValidateException
     */
    public function posts($functionName, $data, $isLogin = false, $timeOut = 30)
    {
        $startTime = microtime();
        $data = json_encode($data);
        $urlDress = env('JAVA_RESOURCE'). $this->prefix . $functionName . '.jhtml';
        $result = $this->Request($urlDress, $data, $isLogin, $timeOut);
        $endTime = microtime();
        $timeWait = number_format(($endTime - $startTime) * 1000, 2);
        //除正式环境外其他环境都写日志
        if (env('APP_ENV') !== 'prod') {
            $context = [
                'wrapper' => $urlDress,
                'data' => $data,
                'time' => $timeWait,
                'type' => 'java-request'
            ];
            \Log::info('java', $context);
        }
        if ($result['resultType'] !== 'success') {
            $context = [
                'wrapper' => $urlDress,
                'data' => $data,
                'time' => $timeWait,
                'result' => $result,
                'type' => 'java-request'
            ];
            \Log::error('java code Exception', $context);
            throw new ValidateException($result['resultMsg']);
        }

        return $result;
    }

    protected function Request($urlDress, $data, $isLogin, $timeout = 30)
    {
        $header = ['Content-Type: application/json'];
        $cookieJar = 'temp/' . scandir('temp', 1)[0];
        if ($isLogin) {
            if (!file_exists('temp'))
                mkdir('temp');
            unlink($cookieJar);
            $cookieJar = tempnam('temp', 'javaCookie');
        }
        $process = curl_init($urlDress);
        curl_setopt($process, CURLOPT_HTTPHEADER, $header);
        curl_setopt($process, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($process, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($process, CURLOPT_POSTFIELDS, $data);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        if ($isLogin) {
            curl_setopt($process, CURLOPT_COOKIEJAR, $cookieJar);
        } else {
            curl_setopt($process, CURLOPT_COOKIEFILE, $cookieJar);
        }
        curl_setopt($process, CURLOPT_POST, 1);
        $data = curl_exec($process);
        $statusCode = curl_getinfo($process, CURLINFO_HTTP_CODE);
        if ($statusCode !== 200) {
            \Log::info('result:' . $data);
            return
                [
                    "resultType" => 'failure',
                    "resultCode" => $statusCode,
                    "resultMsg" => "获取接口数据失败"
                ];
        }

        curl_close($process);
        $result = json_decode($data, true);
        $result['resultCode'] = $statusCode;

        return $result;
    }
}